//
//  SHHPersonCenterTVC.swift
//  GoTravel
//
//  Created by lanou3g on 16/3/4.
//  Copyright © 2016年 SHH. All rights reserved.
//

import UIKit

@objc protocol SHHPersonCenterTVCDelegate {
    func changeLoginState()
}

class SHHPersonCenterTVC: UITableViewController {

    
    let width = UIScreen.mainScreen().bounds.width
    let height = UIScreen.mainScreen().bounds.width/1.5
    
    //背景图
    let bigImageView = UIImageView()
    //头像
    let smallView = UIImageView()
    
    //申明代理
    var delegate:SHHPersonCenterTVCDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()
        self.navigationItem.title = "个人中心"
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "HTHome_Menu"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("showSideView"))
        
        //头部背景图
        self.bigImageView.frame = CGRectMake(0, 0, width, height-69)
        self.bigImageView.image = UIImage(named: "9.jpg")
        self.bigImageView.clipsToBounds = true
        self.bigImageView.contentMode = UIViewContentMode.ScaleAspectFill
        self.bigImageView.userInteractionEnabled = true
        self.tableView.tableHeaderView = self.bigImageView
//        self.view.addSubview(self.bigImageView)
        
        //用户信息
//        let userInfo = SHHGetUser.sharedGetUser
        //头像
        self.smallView.frame = CGRectMake(0, 0, 70, 70)
        self.smallView.image = UIImage(named: "iconfont-unie64d")
//        if (userInfo.photo_url == "") || (userInfo.photo_url == nil) {
//            self.smallView.image = UIImage(named: "iconfont-unie64d")
//        }else{
//            self.smallView.sd_setImageWithURL(NSURL(string: userInfo.photo_url!), placeholderImage: UIImage(named: "iconfont-unie64d"))
//        }
        self.smallView.center = CGPointMake(self.bigImageView.center.x, self.bigImageView.center.y)
        self.smallView.clipsToBounds = true
        self.smallView.contentMode = UIViewContentMode.ScaleAspectFill
        self.smallView.userInteractionEnabled = true
        self.smallView.layer.cornerRadius = 35
        self.smallView.layer.masksToBounds = true
        self.bigImageView.addSubview(self.smallView)
        //添加手势
        let tap = UITapGestureRecognizer(target: self, action: Selector("tapAction:"))
        self.smallView.addGestureRecognizer(tap)
        
//        self.automaticallyAdjustsScrollViewInsets = false
        
        //清除多余的tableview线条
        self.tableView.tableFooterView = UIView()
        //设置分割线
        self.tableView.separatorInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
        
        //注册cell
        self.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell")
    }
    
    //手势的触发事件
    func tapAction(sender:UITapGestureRecognizer) {
        print("头像")
        let modifyVC = SHHModifyUserInfoVC()
        self.navigationController?.pushViewController(modifyVC, animated: true)
    }
    
    func showSideView()->Void {
        
        self.sideMenuViewController.presentLeftMenuViewController()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 4
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

        let array = ["修改资料","我的收藏","清除缓存","退出账户"]
        cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        cell.textLabel?.text = array[indexPath.row]

        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.row == 0 {
            let modify = SHHModifyUserInfoVC()
            self.navigationController?.pushViewController(modify, animated: true)
        }else if indexPath.row == 1 {
            let favoriteTVC = SHHFavoriteTVC()
            self.navigationController?.pushViewController(favoriteTVC, animated: true)
        }else if indexPath.row == 2 {
            self.clearCache()
        }else {
            let alert = UIAlertController(title: nil, message: "是否退出登录", preferredStyle: UIAlertControllerStyle.Alert)
            let defaultAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction) -> Void in
                //判断它是否登录
                let currentUser = AVUser.currentUser()
                if currentUser != nil {
                    AVUser.logOut()
                    self.delegate?.changeLoginState()
                    self.sideMenuViewController.presentLeftMenuViewController()
                }
            })
            
            let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
            alert.addAction(defaultAction)
            alert.addAction(cancelAction)
            self.presentViewController(alert, animated: true, completion: nil)
        }
        
    }
    
    //清除缓存
    func clearCache() {
        
        //获取缓存路径
        let cachesPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
        //打印路径，需要测试的可以往这个路径下放东西
        print(cachesPath!)
        //取出文件夹下所有文件数组
        let files = NSFileManager.defaultManager().subpathsAtPath(cachesPath!)
        //用于统计文件夹内所有文件的大小
        var big = Int()
        
        //快速枚举取出所有文件名
        for p in files! {
            let path = cachesPath!.stringByAppendingString("/\(p)")
            //取出文件属性
            let floder = try! NSFileManager.defaultManager().attributesOfItemAtPath(path)
            //用元组取出文件大小属性
            for (a,b) in floder {
                //只去除文件大小进行拼接
                if a == NSFileSize {
                    big += b.integerValue
                }
            }
        }
        
        //提示框
        let message = "\(big/(1024*1024))M缓存"
        let alert = UIAlertController(title: "清除缓存", message: message, preferredStyle: UIAlertControllerStyle.Alert)
        
        let alertConfirm = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default) { (action:UIAlertAction) -> Void in
            //点击确认进行删除
            for p in files! {
                //拼接路径
                let path = cachesPath!.stringByAppendingString("/\(p)")
                //判断是否可以删除
                if NSFileManager.defaultManager().fileExistsAtPath(path) {
                    //删除
                    try! NSFileManager.defaultManager().removeItemAtPath(path)
                }
            }
        }
        let cancle = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
        
        alert.addAction(alertConfirm)
        alert.addAction(cancle)
        self.presentViewController(alert, animated: true, completion: nil)
        
    }
    
    

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
